<?php
/**
 * 目录管理
 * @since   2018-01-16
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace app\backstage\controller;


use app\model\KmCode as model;
use app\util\ReturnCode;
use app\util\Tools;
use think\Db;
use think\Exception;

class KmCode extends Base {

    /**
     * 获取列表
     */
    public function index() {
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['status'])){
                $query->where('u.status', $postData['status']);
            }
            if(isset($postData['code'])&& $postData['code']){
                $query->where('u.code', $postData['code']);
            }

        };



        $list = model::alias('u')
            ->field('u.*')
            ->where($where)
            ->order('id desc')
            ->limit(( $page - 1 ) * $size , $size)
            ->select();
        if($list){
            $list->append(['statusText',]);
        }


        $count =   model::alias('u')
            ->where($where)
            ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }

    /**
     * 新增
     */
    public function add() {
        $param =  $this->request->post();
        if(!isset($param['content']))return $this->buildFailed(ReturnCode::INVALID, '新葵码不能为空');
        $where = ['statusCheck' => 1,'newKm' => ''];


        Db::startTrans();
        try{


            $content_arr = preg_split("/(,|，)/",$param['content']);
            $adds = [];
            foreach ($content_arr as $item){
                $adds[] = [
                    'code' => $item,
                    'status' => 2,
                    'addTime' => time(),
                ];
            }
            $flag = Db::name('km_code')->insertAll($adds);
            if (!$flag) throw new Exception('导入葵码失败');
            Db::commit();
            return $this->buildSuccess($content_arr);
        }catch(\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }



    /**
     * 编辑
     */
    public function edit() {
        $postData = $this->request->post();
        if (empty($postData['name'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '平台名称必须填写');
        }
        $res = \app\model\Platform::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }



}
